﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using SlamCms.Web;

namespace SlamCms.Data
{
	public static class QueryBuilderExtensions
	{
		public static QueryBuilder FilterTaggedWithSpecificTagsOf(this QueryBuilder slamQuery, ContentItem contentItem)
		{
			return slamQuery.FilterTaggedWithSpecificTags(contentItem.Tags.Select(t => t.Identifier));
		}

		public static QueryBuilder FilterTaggedWithSpecificTags(this QueryBuilder slamQuery, IEnumerable<string> tagIdentifiers)
		{
			// TODO refactor this
			var slamCmsContext = DependencyResolver.Current.GetService<SlamCmsContext>();
			var tagTree = slamCmsContext.GetTagTree();

			var tagsWithNoChildren = tagTree.FindNodes(n => n.Type == TagTreeNodeType.Tag && !n.Children.Any());
			var specificTagIdentifiers = tagsWithNoChildren.Select(n => n.Identifier).Distinct();
			var finalIdentifiers = specificTagIdentifiers.Intersect(tagIdentifiers);

			return slamQuery.FilterTaggedWithAny(finalIdentifiers);
		}
	}
}
